package com.springboot.middleware.middleware_redisson.server.redisson;

import com.springboot.middleware.middleware_redisson.server.dto.DeadDto;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redisson延迟队列消息模型-生产者
 */
@Component
public class RedissonDelayQueuePublisher {
    private static final Logger log = LoggerFactory.getLogger(RedissonDelayQueuePublisher.class);

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 发送消息进入延迟队列
     *
     * @param msg 消息
     * @param ttl 消息存活时间-单位:毫秒
     */
    public void sendDelayMsg(final DeadDto msg, final Long ttl) {
        try {
            final String delayQueueName = "redissonDelayQueue";
            RBlockingDeque<DeadDto> rBlockingDeque = redissonClient.getBlockingDeque(delayQueueName);
            RDelayedQueue<DeadDto> delayedQueue = redissonClient.getDelayedQueue(rBlockingDeque);
            delayedQueue.offer(msg, ttl, TimeUnit.MILLISECONDS);

            log.info("Redisson延迟队列消息模型 - 生产者 - 发送消息入延迟队列 - 消息: {}", msg);
        } catch (Exception e) {
            log.error("Redisson延迟队列消息模型 - 生产者 - 发送消息入延迟队列 - 发生异常: {}", msg, e.fillInStackTrace());
        }
    }
}
